

package ling.archives.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.*;
import ling.archives.domain.Archive;
import ling.archives.domain.ArchiveContent;
import ling.archives.domain.dto.ValueItem3;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import ling.archives.domain.BorrowFile;
//import ling.archives.service.BorrowFileService;
import ling.archives.common.*;
import ling.archives.common.domain.*;

/** 借阅 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-4-14
 */
@Api(tags = "借阅 功能接口")
@RestController
@RequestMapping("/archives/BorrowFile")
public class BorrowFileController extends EQueryController<BorrowFile> {

    //借阅申请

  //：查看资料
    //管理员借阅审批列表
    //借阅列表：关闭借阅

    @ApiOperation("详情")
    @PreAuthorize("@ar.any(@ar.borrowFile.query)")
    @GetMapping(value = "/{id}")
    public Result<BorrowFile> getInfo(@PathVariable("id") Long id) {
        return super.getInfo(id);
    }

    @ApiOperation(value = "分页列表",notes = "借阅列表查看")
    @PreAuthorize("@ar.any(@ar.borrowFile.list)")
    @GetMapping("list")
    public ResultRows<BorrowFile> list(BorrowFile dto, PageDomain pageRequest) {
        return queryPage(dto, pageRequest);
    }

    @ApiOperation(value = "用户借阅申请列表",notes = "借阅列表查看")
    @PreAuthorize("@ar.any(@ar.borrowFile.list)")
    @GetMapping("userApprovalList")
    public ResultRows<BorrowFile> userApprovalList(BorrowFile dto, PageDomain pageRequest) {
        dto.setBorrowId(getUserId());
        return queryPage(dto, pageRequest);
    }
    @ApiOperation(value = "已借阅档案查询",notes = "需要提供借阅id,会根据借阅id限制查询内容")
    @PreAuthorize("@ar.any(@ar.archive.list)")
    @GetMapping("archives")
    public ResultRows<Archive> archives(Long borrowFileId,Archive dto, PageDomain pageRequest) {
//        var borrow = queryHelper.entityQuery(BorrowFile.class)
//                .whereById(borrowFileId)
//                .where(b -> b.status().eq("1"))
//                .where(b -> b.beginTime().le(new Date()))
//                .where(b -> b.endTime().ge(new Date()))
//                .firstOrNull();
//        if(borrow==null)
//            return ResultRows.bad("借阅信息未找到");
//        if(!Objects.equals(borrow.getBorrowId(), getUserId()))
//            return ResultRows.bad("借阅人不符");
//        var filsIdsJson = borrow.getFilesId();
//        var ids = DataUtil.toObjByJson(filsIdsJson, Long[].class);
        var checkRe = checkReRange(borrowFileId);
        if (!checkRe.isSuccess())
            return ResultRows.byResule((Result) checkRe);
        var ids = checkRe.getData();
        pageRequest = gainPageDomain(pageRequest);
        var pitem = queryHelper.entityQuery(Archive.class)
                .where(a -> a.id().in(ids))
                .whereObject(dto != null, dto);
        if (pageRequest instanceof ObjectSort)
            pitem.orderByObject((ObjectSort) pageRequest);
        var pData = pitem.orderBy(p -> p.id().desc())
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        return toResultRows(pData);
    }
    Result<Long[]> checkReRange(Long borrowFileId){
        if(borrowFileId==null||borrowFileId<1)
            return Result.bad("借阅id错误");
        var borrow = queryHelper.entityQuery(BorrowFile.class)
                .whereById(borrowFileId)
                .where(b -> b.status().eq("1"))
                .where(b -> b.beginTime().le(new Date()))
                .where(b -> b.endTime().ge(new Date()))
                .firstOrNull();
        if(borrow==null)
            return ResultRows.bad("借阅信息未找到");
        if(!Objects.equals(borrow.getBorrowId(), getUserId()))
            return ResultRows.bad("借阅人不符");
        var filsIdsJson = borrow.getFilesId();
        var ids = DataUtil.toObjByJson(filsIdsJson, Long[].class);
        return Result.ok(ids);
    }
    @ApiOperation(value = "已借阅档案内容查询",notes = "需要提供借阅id,会根据借阅id限制查询内容")
    @PreAuthorize("@ar.any(@ar.archive.list)")
    @GetMapping("archiveContents")
    public ResultRows<ArchiveContent> archiveContents(Long borrowFileId, ArchiveContent dto, PageDomain pageRequest) {
        var checkRe = checkReRange(borrowFileId);
        if (!checkRe.isSuccess())
            return ResultRows.byResule((Result) checkRe);
        var ids = checkRe.getData();
        var pitem = queryHelper.entityQuery(ArchiveContent.class)
                .where(a -> a.archive().doccId().in(ids))
                .whereObject(dto != null, dto);
        if (pageRequest instanceof ObjectSort)
            pitem.orderByObject((ObjectSort) pageRequest);
        var pData = pitem.orderBy(p -> p.id().desc())
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        return toResultRows(pData);
    }

    @ApiOperation("关闭借阅")
    @PreAuthorize("@ar.any(@ar.borrowFile.edit)")
    @Log(title = "借阅", businessType = BusinessType.INSERT)
    @PostMapping("cloaseBorrow")
    public Result cloaseBorrow(Long id) {
        var entity = queryHelper.entityQuery(BorrowFile.class).whereById(id).firstOrNull();
        if (Objects.equals(entity.getStatus(), "1"))
            entity.setStatus("5");
        else
            return Result.bad("必须为通过的借阅才可以关闭");
        return super.edit(entity);
    }
    @ApiOperation("新增借阅申请")
    @PreAuthorize("@ar.any(@ar.borrowFile.add)")
    @Log(title = "借阅", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public Result add(@Validated @RequestBody BorrowFile entity) {
        var idStr=entity.getFilesId();
        if(StringUtils.isBlank( idStr)||!idStr.startsWith("["))
            return Result.bad("档案id格式错误");
        var ids=DataUtil.toObjByJson(idStr,Long[].class);
        var arList=queryHelper.entityQuery(Archive.class).where(a -> a.id().in(ids)).toList();
        if(ids.length!=arList.size())
            return Result.bad("文件id不正确");
        var titleArr=arList.stream().map(p->p.getTitle()).toArray(String[]::new);
        entity.setFilesName(DataUtil.toJson(titleArr));
        entity.setStatus("3");
        entity.setBorrowName(getLoginUser().getUser().getNickName());
        entity.setBorrowId(getUserId());

        return super.add(entity);
    }
    @ApiOperation(value = "审批",notes = "参数123依次为：流程id; 通过1驳回2; 备注")
    @PreAuthorize("@ar.any(@ar.borrowFile.edit)")
    @Log(title = "借阅", businessType = BusinessType.UPDATE)
    @PostMapping("Approval")
    public Result Approval(@RequestBody ValueItem3<Long,String,String> dto) {
        var id=Convert.convert(Long.class,dto.getValue1());
        var old=queryHelper.entityQuery(BorrowFile.class).whereById(id).firstOrNull();
        if(!Objects.equals(old.getStatus(), "3"))
            return Result.bad("审批状态必须为已提交");
        old.setStatus(Objects.equals(dto.getValue2(), "1") ?"1":"2");
        old.setDescr(dto.getValue3()+"\r\n"+old.getDescr());
        return super.edit(old);
    }

//    @ApiOperation("删除")
//    @PreAuthorize("@ar.any(@ar.borrowFile.remove)")
//    @Log(title = "借阅", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public Result remove(@PathVariable("ids") Long[] ids) {
//        return super.remove(Arrays.stream(ids).toArray());
//    }
//
//    @ApiOperation("编辑")
//    @PreAuthorize("@ar.any(@ar.borrowFile.edit)")
//    @Log(title = "借阅", businessType = BusinessType.UPDATE)
//    @PostMapping("edit")
//    public Result edit(@Validated @RequestBody BorrowFile entity) {
//        return super.edit(entity);
//    }

//    @ApiOperation("导出")
//    @PreAuthorize("@ar.any(@ar.borrowFile.export)")
//    @Log(title = "借阅", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(BorrowFile entity, PageDomain pageRequest, HttpServletResponse response) {
//        super.export(entity, pageRequest, null, response);
//    }
}